<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Api extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/home
	 *	- or -  
	 * 		http://example.com/index.php/home/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
    function __construct()
    {
        parent::__construct(); 
		//Set Cache
		//$this->output->cache(2);
		//Load Database
		//$this->DB_LIVE = $this->load->database("you2play_live",TRUE);
		//Load model
		$this->load->model('api_model');
		//Set Templates
		$this->folder_templates = "api/";
      	//Set Script Default
   		$this->data['js']    = array('');
    	//Set Style Default
    	$this->data['css']   = array('');	
        //Set Script External Default	
        $this->data['external_js']  = '';
        //Set style External Default	
        $this->data['external_css'] = '';	
		//Set Upload Folder
		$this->upload_folder = (!ONIDEV ? $this->config->item('path_asset_url').'assets/uploads/':realpath('assets/uploads/').'/');
    }
	 
	/*Partner 555.in.th*/
	public function www555inth()
	{
		$allow_ip = '116.12.204.156';
		$request_ip = $this->input->server('HTTP_X_FORWARDED_FOR');
		$this->api_model->www555inthExport();
/*		if($request_ip == $allow_ip):*/
		
/*		else:
			die('This Url allow only our partner. Please feel free to contact webmaster@you2play.com.');
		endif;*/
		exit;
	}
	 
	/*Partner Popdio*/
	public function popdio()
	{
		/*Set User && Password*/
		$username = "popdio";
		$password = "12345";
		
		if (!isset($_SERVER['PHP_AUTH_USER']) || !($_SERVER['PHP_AUTH_USER'] == $username && $_SERVER['PHP_AUTH_PW'] == $password)):
		    header('WWW-Authenticate: Basic realm="PMD+ CO.,LTD"');
		    header('HTTP/1.0 401 Unauthorized');
		    echo 'PMD+ CO.,LTD : Please Login first.';
		    exit;
		else:
			//set UTF-8
			header('Content-Type:application/json; charset=UTF-8');
			$request_body = @file_get_contents('php://input');
			//Load Json Data to Object
			$dataJson = @json_decode($request_body);
			if(!is_array($dataJson)): //Single Request
				if(empty($dataJson) || $dataJson->jsonrpc != '2.0' || empty($dataJson->method)):
					$data = $this->showError(-32600);					
				else:
					############# API Activate #############
					switch($dataJson->method):
						case 'listContents': //Show All Contents
							$data = $this->api_model->listContents($dataJson);
						break;
					endswitch;	
					############# End API Activate #############	
				endif;
			else: // Multi Request
				$data = array();
				foreach($dataJson as $value):
					if(empty($value) || $value->jsonrpc != '2.0' || empty($value->method)):
						$data[] = $this->showError(-32600);	
					else:
						############# API Activate #############	
						############# End API Activate #############
					endif;
				endforeach;
			endif;
			echo json_encode($data);
		endif;
	}
	
	private function showError($str)
	{
		switch($str):
			case -32600:
				$fields = array(
					'jsonrpc' => '2.0', //version
					'id' => null, //number/string
					'error' => array( //parameter
							'code' => -32600,
							'message' => 'Invalid Request'
					)
				);		
			break;
			case -32700:
				$fields = array(
					'jsonrpc' => '2.0', //version
					'id' => null, //number/string
					'error' => array( //parameter
							'code' => -32700,
							'message' => 'Parse error'
					)
				);		
			break;			
		endswitch;
		return $fields;
	}
	
	public function contest($id = null,$method = "listContents")
	{
		//http://api.you2play.com/contest/2/listContents/?params[contentType]=FS
		//set UTF-8
		//header('Content-Type:text/html; charset=UTF-8');
		
		//set POST variables
		$url = 'http://api.you2play.com/popdio';
		/*Single*/
		$fields = array(
		            'jsonrpc' => '2.0', //version
		            'id' => $id, //number/string
		            'method' => $method, //method
		            'params' => (!isset($_GET['params']) ? array():$_GET['params']) //parameter
		        );
		/*Multiple*/
/*		$fields = array();	
		$fields[] = array(
		            'jsonrpc' => '2.0', //version
		            'id' => $id, //number/string
		            'method' => $method, //method
		            'params' => (!isset($_GET['params']) ? array():$_GET['params']) //parameter
		        );
		$fields[] = array(
		            'jsonrpc' => '2.0', //version
		            'id' => $id, //number/string
		            'method' => $method, //method
		            'params' => (!isset($_GET['params']) ? array():$_GET['params']) //parameter
		        );*/				

		//url-ify the data for the POST
		$fields_string = json_encode($fields);
		
		// jSON URL which should be requested
		$json_url = $url;
		 
		$username = 'popdio';  // authentication
		$password = '12345';  // authentication
		 
		// jSON String for request
		$json_string = $fields_string;
		 
		// Initializing curl
		$ch = curl_init( $json_url );
		 
		// Configuring curl options
		$options = array(
			CURLOPT_POST => true,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_USERPWD => $username . ":" . $password,   // authentication
			CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
			CURLOPT_POSTFIELDS => $json_string
		);
		 
		// Setting curl options
		curl_setopt_array( $ch, $options );
		 
		// Getting results
		$result =  curl_exec($ch); // Getting jSON result string
		
		echo $result;
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */